package com.googlecode.webduff.methods;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.webduff.WebdavStatus;

public class MethodResponse {
	
	private Integer statusCode;
	
	private String contentType;
	
	private long contentLength;
	
	private Map<String, String> headerData;

	private Map<String, Long> dateHeaderData;
	
	private ServletResponse originalHttpResponse;
	
	public MethodResponse(HttpServletResponse response) throws IOException {
		this(WebdavStatus.SC_OK, response);
	}
	
	public MethodResponse(Integer code, HttpServletResponse response) throws IOException {
		originalHttpResponse = response;
		statusCode = code;
		headerData = new HashMap<String, String>();
		dateHeaderData = new HashMap<String, Long>();
	}
	
	public Map<String, String> getHeaders() {
		return headerData;
	}
	
	public MethodResponse setHeader(String name, String content) {
		headerData.put(name, content);
		return this;
	}
	
	public Integer getStatusCode() {
		return statusCode;
	}
	
	public MethodResponse setStatusCode(Integer aCode) {
		statusCode = aCode;
		return this;
	}
	
	public Writer getWriter() throws IOException {
		return originalHttpResponse.getWriter();
	}
	
	public String getContentType() {
		return contentType;
	}
	
	public long getContentLength() {
		return contentLength;
	}
	
	public MethodResponse setDateHeader(String name, long content) {
		dateHeaderData.put(name, content);
		return this;
	}

	public Map<String, Long> getDateHeaders() {
		return dateHeaderData;
	}

	public MethodResponse setContentLength(long resourceLength) {
		contentLength = resourceLength;
		return this;
	}

	public MethodResponse setContentType(String mimeType) {
		contentType = mimeType;
		return this;
	}
	
	public void handle(HttpServletResponse theResponse) throws IOException {
		// handle header
		if(getHeaders().size() > 0) {
			for(String name : getHeaders().keySet()) {
				theResponse.addHeader(name, getHeaders().get(name));
			}
		}
		
		// handle date headers
		if(getDateHeaders().size() > 0) {
			for(String name : getDateHeaders().keySet()) {
				theResponse.addDateHeader(name, getDateHeaders().get(name));
			}
		}
		
		// handle status code & content type
		theResponse.setStatus(getStatusCode());
		//theResponse.setContentType(getContentType());
	}

	public OutputStream getOutputStream() throws IOException {
		return originalHttpResponse.getOutputStream();
	}

}